<?php
/**
 * vim:fdm=marker:ts=4:sw=4
 * @fileoverview
 * 后台
 */

require_once('include/common.php');

// {{{ 常量设置
/*----------------------------------------------------------------------------*/
// 允许的功能
$valid_func = array(
	'login',				// 用户登录
	'logout',				// 注销
	'update',				// 修改自己的信息
	'register',				// 新用户申请
	'admit',				// 审核申请
	'manage',				// 管理帐号
);
// }}}

/*----------------------------------------------------------------------------*/
// main
$fn = $_GET['f'];
if ($fn && in_array($fn, $valid_func)) {
	$cmd = "do_" . $fn;
	$cmd();
} else {
	redirect("/");
}



/*----------------------------------------------------------------------------*/
// 各种动作定义

// {{{ do_login()
/**
 * 用户登录
 */
function do_login() {
	global $db_user;

	$username = strtolower(get_post('username'));
	$password = get_post('password');

	$users = $db_user->read_all();
	
	$login_success = false;
	foreach ($users as $user) {
		if ($user['username'] == $username && $user['password'] == md5($password)) {
			if ($user['validuser']) {
				$_SESSION['userid'] = $user['id'];
				$_SESSION['username'] = $user['username'];
				if ($user['admin']) $_SESSION['admin'] = true;
				$login_success = true;
			} else {
				$msg = "您的帐号尚未经管理员批准，请稍候！";
			}
			break;
		}
	}

	if ($login_success) {
		redirect('/');
	} else {
		if (!$msg) $msg = "您输入的用户名或密码有误！";
		redirect("/?err=login&msg=" . urlencode($msg) . "#login");
	}
}
// }}}


// {{{ do_logout()
/**
 * 注销
 */
function do_logout() {
	require_login();

	session_destroy();
	redirect('/');
}
// }}}


// {{{ do_update()
/**
 * 修改自己的信息
 */
function do_update() {
	global $db_user;

	require_login();
	$password = get_post('blog_password');
	$password_sure = get_post('blog_password_sure');
	$blog_name = get_post('blog_name');
	$blog_url = get_post('blog_url');
	$logo_url = get_post('logo_url');
	$description = get_post('description');
	$suicide = get_post('suicide');

	$user_id = get_current_userid();

	// 如果要自杀掉自己的账户……
	if ($suicide) {
		$users = $db_user->read_all();

		// 查找该用户
		$count = count($users);
		for ($i = 0; $i < $count; $i++) {
			if ($users[$i]['id'] == $user_id) break;
		}

		// 删除之
		array_splice($users, $i, 1);

		$db_user->write_all($users);

		redirect('/b.php?f=logout');
		exit;
	}

	$user = $db_user->read($user_id);

	if ($password != "") {
		if ($password == $password_sure) {
			$user['password'] = md5($password);
		} else {
			redirect("/?err=update&msg=" . urlencode('两次输入的密码不一致！') . "#update");
			exit;
		}
	}

	$user['id']          = $user_id;
	$user['blog_name']   = $blog_name;
	$user['blog_url']    = $blog_url;
	$user['logo_url']    = $logo_url;
	$user['description'] = $description;

	$db_user->write($user_id, $user);

	redirect('/#update');
}
// }}}


// {{{ do_register()
/**
 * 新用户申请
 */
function do_register() {
	global $db_user;

	if (!is_registerable_now()) {
		redirect("/?err=register#joinus");
		exit;
	}

	$username = strtolower(get_post('username'));
	$password = get_post('password');
	$email    = strtolower(get_post('email'));
	$blog_name = get_post('blog_name');
	$blog_url = strtolower(get_post('blog_url'));
	$logo_url = strtolower(get_post('logo_url'));
	$description = get_post('description');

	$users = $db_user->read_all();

	$error = '';

	// 判断是否存在重名用户
	foreach ($users as $user) {
		if ($user['username'] == $username) {
			$error = '您的用户名已被人占用，请换一个试试！';
			break;
		}
	}

	// 检查各个输入框是否都已经填写完毕
	$validate = array(
		'username'  => array(3, 16, "用户名长度为%d～%d个字符。"),
		'password'  => array(3, 16, "密码长度为%d～%d个字符。"),
		'email'     => array(6, 32, "电子邮箱长度为%d～%d个字符。"),
		'blog_name' => array(1, 100, "博客名称长度为%d～%d个字符。"),
		'blog_url'  => array(1, 100, "博客地址长度为%d～%d个字符。"),
//		'logo_url'  => array(1, 100, "图标地址长度为%d～%d个字符。"),
		'description' => array(1, 200, "加入原因长度为%d～%d个字符。"),
	);

	foreach ($validate as $name => $rule) {
		if ($error) break;
		$error = check_length($$name, $rule[0], $rule[1], $rule[2]);
	}

	// 错误处理
	if ($error) {
		// 将用户已经输入过的内容保存到session中
		foreach (array('username', 'email', 'blog_name', 'blog_url', 'logo_url', 'description') as $name) {
			$_SESSION[$name] = $$name;
		}
		redirect("/?err=register&msg=" . urlencode($error) . "#joinus");
		exit;
	}

	// 真正的注册处理
	$max_id = $db_user->max_id();
	$user_id = $max_id + 1;

	$user = array(
		'id'			=> $user_id,
		'username'		=> $username,
		'password'		=> md5($password),
		'email'			=> $email,
		'blog_name'		=> $blog_name,
		'blog_url'		=> $blog_url,
		'logo_url'		=> $logo_url,
		'description'	=> $description,
		'validuser'		=> 0,
		'admin'			=> 0,
	);

	$db_user->write($user_id, $user);

	session_destroy();

	redirect('/?err=register&msg=' . urlencode('您的申请已经成功提交，请等待管理员审核。') . '#joinus');
	exit;
}
// }}}


// {{{ do_admit()
/**
 * 审核申请
 */
function do_admit() {

	global $db_user;

	// 提交的审核结果
	if (!empty($_POST['admit'])) {
		$admits = $_POST['admit'];
	} else {
		$admits = array();
	}


	if (is_array($admits)) {

		$users = $db_user->read_all();

		foreach (array_keys($admits) as $user_id) {

			// 如果选择的是“保留”则继续下一条
			if ($admits[$user_id] == 'keep') continue;

			$count = count($users);
			for ($i = 0; $i < $count; $i++) {
				if ($users[$i]['id'] == $user_id) break;
			}

			// 如果该用户还没有通过申请
			if ($i < $count && $users[$i]['validuser'] == 0) {
				if ($admits[$user_id] == 'allow') {
					$users[$i]['validuser'] = 1;			// 通过
				} else if ($admits[$user_id] == 'deny') {
					$users[$i]['validuser'] = 2;			// 拒绝
				} else if ($admits[$user_id] == 'remove') {
					array_splice($users, $i, 1);
				}

			}
		}

		// 写入数据库
		$db_user->write_all($users);
	}

	redirect('/');
	exit;
}
// }}}


// {{{ do_manage()
/**
 * 管理现有账户
 */
function do_manage() {
	global $db_user;

	// 提交的审核结果
	if (!empty($_POST['manage'])) {
		$manages = $_POST['manage'];
	} else {
		$manages = array();
	}

	if (is_array($manages)) {

		$users = $db_user->read_all();

		foreach (array_keys($manages) as $user_id) {

			// 如果选择的是“保留”则继续下一条
			if ($manages[$user_id] == 'keep') continue;

			$count = count($users);
			for ($i = 0; $i < $count; $i++) {
				if ($users[$i]['id'] == $user_id) break;
			}

			// 如果该用户已经通过申请
			if ($i < $count && $users[$i]['validuser'] == 1) {
				if ($manages[$user_id] == 'disallow') {
					$users[$i]['validuser'] = 0;			// 撤销审核
					$users[$i]['admin'] = 0;				// 取消可能存在的管理员权限
				} else if ($manages[$user_id] == 'remove') {
					array_splice($users, $i, 1);
				}

			}
		}

		// 写入数据库
		$db_user->write_all($users);
	}

	redirect('/');
	exit;
}
// }}}



?>
